// import CryptoJS from 'cryptojs';
import {imgBaseUrl} from '../../config/env';
import wxS from '../../service/wxService';

// cookie方法
export	var cookieUtil = {
	load: function() {
		var tC = document.cookie.split('; ');
		var tO = {};
		var a = null;
		for (var i = 0; i < tC.length; i++) {
			a = tC[i].split('=');
			tO[a[0]] = a[1];
		}
		return tO;
	},
	get: function(name) {
		var value = this.load()[name];
		if (value) {
			try {
				return decodeURIComponent(value);
			} catch(e) {
				return unescape(value);
			}
		} else {
			return '';
		}
	},
	set: function(name, value, options) {
		options = (typeof(options) == 'object') ? options: {
			day: options
		};
		var path = options.path || '/';
		var domain = options.domain || '';
		var exptime = 0;
		if (options.day) {
			exptime = 1000 * 60 * 60 * 24 * options.day;
		} else if (options.hour) {
			exptime = 1000 * 60 * 60 * options.hour;
		} else if (options.minute) {
			exptime = 1000 * 60 * options.minute;
		} else if (options.second) {
			exptime = 1000 * options.second;
		}
		var exp = new Date(),
			expires = '';
		if (exptime > 0) {
			exp.setTime(exp.getTime() + exptime);
			expires = '; expires=' + exp.toGMTString();
		}
		domain = (domain) ? ('; domain=' + domain) : '';
		document.cookie = name + '=' + escape(value || '') + '; path=' + path + domain + expires;
	},
	del: function(name, options) {
		options = options || {};
		var path = '; path=' + (options.path || '/');
		var domain = (options.domain) ? ('; domain=' + options.domain) : '';
		document.cookie = name + '=' + path + domain + '; expires=Thu,01-Jan-70 00:00:01 GMT';
	}
};
// 字符串操作
export var stringUtil = {
	getQueryValue: function(str, name) {
		if (!name) {
			name = str;
			str = location.search;
		}
		var reg = new RegExp("(^|&|\\?|#)" + name + "=([^&]*)(&|\x24)", "");
		var match = str.match(reg);
		return (match && match[2] || '').trim();
	},
	getQueryJSON: function(str) {
			str = str || location.search;
			if (str.indexOf('?') < 0) return {};
			var query = str.substr(str.indexOf('?') + 1),
				params = query.split('&'),
				len = params.length,
				result = {},
				key,
				value,
				item,
				param;
			for (var i = 0; i < len; i++) {
				param = params[i].split('=');
				key = param[0];
				value = param[1];
				item = result[key];
				if ('undefined' == typeof item) {
					result[key] = value;
				} else if (Object.prototype.toString.call(item) == '[object Array]') {
					item.push(value);
				} else {
					result[key] = [item, value];
				}
			}
			return result;
		}
};
// 浏览器判断
export var browserUtil = function() {
	var channel = stringUtil.getQueryValue('_channel_') || sessionStorage.getItem('debug.browser') || '';
	var ua = navigator.userAgent.toLowerCase();
	var weixin = !!ua.match(/micromessenger/i);
	var jfmore = ua.match(/(ios|android)_jfmore_(\d\.\d\.\d)/i), appver = (jfmore && jfmore[2].trim()) || '';
	var obj = {
		ios: !!ua.match(/(iphone|ipod|ipad);?/i),
		android: !!ua.match(/android/i),
		weixin: weixin || (channel == 'weixin'),
		jfmore: appver || ((channel == 'jfmore') ? '0.0.0': ''),
		dev: !!location.hostname.match(/dev/),
		beta: !!location.hostname.match(/stg/),
		uat: !!location.hostname.match(/uat/),
		prd: !location.hostname.match(/dev|stg|uat/)
	};
	obj.envo = obj.dev ? 'dev' : obj.stg ? 'stg' : obj.uat ? 'uat' : 'prd';
	//
	var pageStatus = {};
	var pageEvents = [];
	if (obj.ios) {
		window.addEventListener('pagehide', function() {
			pageStatus.hide = true;
			pageStatus.show = false;
		});
		window.addEventListener('pageshow', function() {
			if (pageStatus.hide) {
				pageEvents.map(function(callback) {
					callback();
				});
			}
			pageStatus.hide = false;
			pageStatus.show = true;
		});
	}
	obj.checkRefresh = function(callback) {
		if (!this.ios) {
			pageEvents.push(callback);
			return false;
		}
	};
	obj.goBack = function() {
		if (document.referrer) {
			history.back();
		} else {
			if (this.jfmore) {
				if (this.jfmore > '0.0.0') {
					jfNative.open('device', 'closewebview');
				} else {
					console.log('关闭Webview');
				}
			}
		}
	};
	return obj;
};

// 添加数字签名
export var createSign = function(data) {
	let keys = [], sign = '', item, i;
	for (item in data) {
		if (item != 'sign') {
			keys.push(item);
		}
	}
	keys.sort();
	for (i=0; i<keys.length; i++) {
		sign += keys[i] + data[keys[i]];
	}
	// sign += '09FB84B1-D90E-4C14-84DB-DEE924A87B51';
	sign += '123456';// 测试环境

	return Crypto.MD5(sign).toString();
};

// 用户登录态相关
export	var userUtil = {
	data: {},
	init: function() {
		// 全局token处理
		var token = cookieUtil.get('login_token') || '';
		this.data = JSON.parse(sessionStorage.getItem('jflm.user') || '{}');
		//
		if (!this.data.token && token) {
			this.set('token', token);
		}
	},
	set: function(item, data) {
		if (typeof(data) != 'undefined') {
			this.data[item] = data;
		} else {
			this.data = item;
		}
		sessionStorage.setItem('jflm.user', JSON.stringify(this.data));
		cookieUtil.set('login_token', this.data.token);
	},
	get: function(item) {
		return (item) ? this.data[item]: this.data;
	},
	check: function() {
		return (!!this.get('token'));
	},
	// checkLogin(url);
	// checkLogin(callback);
	checkLogin: function(callback, beforeLogin) {
		var that = this, url = '', isApp = !!navigator.userAgent.match(/jfmore/);
		if (typeof(callback) == 'string') {
			url = callback;
			callback = function() {
				location.href = url;
			};
		}
		if (this.check()) {
			callback(this.get());
		} else {
			if (isApp) {
				window.onLoginSuccess = function(res) {
					that.set(res);
					callback(res);
				};
				jfNative.open('user', 'login', null, 'onLoginSuccess');
			} else {
				if (beforeLogin) {
					beforeLogin();
				}
				var _channel = stringUtil.getQueryValue('channel_source'), channel_source = (_channel ? '&channel_source=' + _channel : "");
				location.href = imgBaseUrl+'login/getlogincode.htm?callback='+ encodeURIComponent(url || location.href) + channel_source;
			}
		}
	}
};

	// native方法封装
export var jfNative = {
		//加载url，引起宿主的url的改变
		loadUrl: function(url) {
			console.log('--loadNativeUrl--');
			console.log(url);
			var f = document.createElement("iframe");
			f.setAttribute("src", url);
			f.setAttribute("style", "display:none;");
			f.setAttribute("height", "0");
			f.setAttribute("width", "0");
			f.setAttribute("frameborder", "0");
			document.body.appendChild(f);
			//发起请求后这个iframe就没用了，所以把它从dom上移除掉
			f.parentNode.removeChild(f);
			f = null;
		},
		open: function(host, action, data, callback) {
			//exam native://{host}?action={action}[&data={data}][&callback={callback}]
			var url = 'native://'+ host +'?action='+ action;
			if (data) {
				url += '&data='+ encodeURIComponent(JSON.stringify(data));
			}
			if (callback) {
				url += '&callback='+ callback;
			}
			this.loadUrl(url);
		}
	};
    //   微信 分享
export var wxShare = function(wx){
	var h = location.href;
	var index = h.indexOf("#");
	if(index && index > 0) {
		h = h.substring(0,index);
	}
	h = encodeURIComponent(h);
	wxS.wxShare({url:h})
	.then(data => {
		wx.config({
			debug: false,
			appId: "wxf3e807fb8699fcf2",
			timestamp: data.info.timestamp,
			nonceStr: data.info.noncestr,
			signature: data.info.signature,
			jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone']
		});
		wx.ready(function(){
			data.title = "玩游戏，挣积分，兑话费！";
			data.content = "我在这里兑换了10元话费，你也来试试。";
			data.shareurl = "http://5beans.cn/wechatMP/mall/#/main";
			data.imageurl = location.origin +"/wechatMP/static/image/wxshare.jpg";

			wx.onMenuShareTimeline({
				title: data.title, // 分享标题
				link: data.shareurl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				imgUrl: data.imageurl, // 分享图标
				success: function () {
					// 用户确认分享后执行的回调函数
				},
				cancel: function (e) {
					// 用户取消分享后执行的回调函数
				   // alert("朋友圈："+e.toString())
				}
			});
			wx.onMenuShareAppMessage({
				title: data.title, // 分享标题
				desc: data.content, // 分享描述
				link: data.shareurl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				imgUrl: data.imageurl, // 分享图标
				type: '', // 分享类型,music、video或link，不填默认为link
				dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
				success: function () {

				},
				cancel: function () {
					// 用户取消分享后执行的回调函数
				}
			});
			wx.onMenuShareQQ({
				title: data.title, // 分享标题
				desc: data.content, // 分享描述
				link: data.shareurl, // 分享链接
				imgUrl: data.imageurl, // 分享图标
				success: function () {
				   // 用户确认分享后执行的回调函数
				},
				cancel: function () {
				   // 用户取消分享后执行的回调函数
				}
			});
			wx.onMenuShareWeibo({
				title: data.title, // 分享标题
				desc: data.content, // 分享描述
				link: data.shareurl, // 分享链接
				imgUrl: data.imageurl, // 分享图标
				success: function () {
				   // 用户确认分享后执行的回调函数
				},
				cancel: function () {
					// 用户取消分享后执行的回调函数
				}
			});
			wx.onMenuShareQZone({
				title: data.title, // 分享标题
				desc: data.content, // 分享描述
				link: data.shareurl, // 分享链接
				imgUrl: data.imageurl, // 分享图标
				success: function () {
				   // 用户确认分享后执行的回调函数
				},
				cancel: function () {
					// 用户取消分享后执行的回调函数
				}
			});
	});

});
}
